package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.Article.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.AggBehaviorDTO;
import com.heima.utils.common.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Transactional
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 计算热文章
     */
    @Override
    public void computeHotArticle() {
        //1 查询前5天的 （已上架、未删除） 文章数据
        String date = LocalDateTime.now().minusDays(5)
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00"));

        List<ApArticle> articleList = apArticleMapper.selectArticleByDate(date);
        //2 计算热点文章分值
        List<HotArticleVo> hotArticleVoList = computeArticleScore(articleList);
        //3 为每一个频道缓存热点较高的30条文章
        cacheTagToRedis(hotArticleVoList);
    }

    @Override
    public void updateApArticle(AggBehaviorDTO aggBehavior) {
        // 1. 根据id 查询文章数据
        ApArticle article = apArticleMapper.selectById(aggBehavior.getArticleId());
        if (article == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "对应的文章数据不存在");
        }
        // 2. 将聚合行为文章数据  和  文章表中的统计数据  累加一起
        // 更新阅读量
        Integer views = article.getViews() == null ? 0 : article.getViews();
        article.setViews((int) (views + aggBehavior.getView()));
        // 更新点赞量
        Integer likes = article.getLikes() == null ? 0 : article.getLikes();
        article.setLikes((int) (likes + aggBehavior.getLike()));
        // 更新评论量
        Integer comment = article.getComment() == null ? 0 : article.getComment();
        article.setComment((int) (comment + aggBehavior.getComment()));
        // 更新收藏量
        Integer collection = article.getCollection() == null ? 0 : article.getCollection();
        article.setCollection((int) (collection + aggBehavior.getCollect()));
        apArticleMapper.updateById(article);
        // 3. 重新计算文章热度得分
        Integer score = computeScore(article);
        // 4. 如果文章是今天发布的  热度 * 3
        // 当前时间
        String now = DateUtils.dateToString(new Date());
        // 发布时间
        String publishTime = DateUtils.dateToString(article.getPublishTime());
        if (publishTime.equals(now)) {
            score = score * 3;
        }
        // 5.  更新当前文章所在频道的缓存
        updateArticleCache(article, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + article.getChannelId());
        // 6.  更新推荐频道的缓存
        updateArticleCache(article, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }


    private void updateArticleCache(ApArticle article, Integer score, String cacheKey) {
        // 1. 从redis中 查询出 对应的热点文章列表
        String hotArticleJson = redisTemplate.opsForValue().get(cacheKey);
        List<HotArticleVo> hotArticleVoList = JSON.parseArray(hotArticleJson, HotArticleVo.class);
        // 2. 判断当前文章是否 存在热点文章列表中
        boolean isHas = false;
        for (HotArticleVo articleVo : hotArticleVoList) {
            // 3.    如果存在  直接更新文章 score热度值
            if (articleVo.getId().equals(article.getId())) {
                // 当前文章已经存在热点文章中，更新得分即可
                articleVo.setScore(score);
                isHas = true;
                break;
            }
        }
        // 4.    如果不存在  直接将当前文章 加入到热点文章列表
        if (!isHas) {
            HotArticleVo articleVo = new HotArticleVo();
            BeanUtils.copyProperties(article, articleVo);
            articleVo.setScore(score);
            hotArticleVoList.add(articleVo);
        }
        // 5.  重新将热点文章列表 按照热度降序排序   截取前30条文章
        hotArticleVoList = hotArticleVoList.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        // 6.   将文章集合 重新 存入到redis中
        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVoList));
    }

    @Autowired
    AdminFeign adminFeign;
    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 3 频道缓存热点较高的30条文章
     *
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        //1 查询所有的频道列表
        ResponseResult<List<AdChannel>> responseResult = adminFeign.selectChannels();
        if (responseResult.getCode() == 0) {
            List<AdChannel> list = responseResult.getData();
            //2 遍历频道列表，筛选当前频道下的文章
            for (AdChannel adChannel : list) {
                //3 给每个频道下的文章进行缓存
                List<HotArticleVo> hotArticleVos = hotArticleVoList.stream()
                        // 当前频道下的文章列表
                        .filter(hotArticle -> hotArticle.getChannelId().equals(adChannel.getId()))
                        .collect(Collectors.toList());
                sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + adChannel.getId());
            }
        }
        //4 给推荐频道缓存30条数据  所有文章排序之后的前30条
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 缓存热点文章
     *
     * @param hotArticleVos
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String cacheKey) {
        // 对文章进行排序
        hotArticleVos = hotArticleVos.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVos));
    }

    /**
     * 2 计算热点文章的分值
     *
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> articleList) {
        // 定义返回集合
        return articleList.stream().map(apArticle -> {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle, hotArticleVo);
            // 2.1计算文章分值算法
            Integer score = computeScore(apArticle);
            hotArticleVo.setScore(score);
            return hotArticleVo;
        }).collect(Collectors.toList());
    }

    /**
     * 2.1计算文章分值算法
     *
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        int score = 0;
        // 阅读 1
        if (apArticle.getViews() != null) {
            score += apArticle.getViews() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        // 点赞 3
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        // 评论 5
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        // 收藏 8
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}